package zero.springdemo.springquartzdemo.core.quartz

import org.quartz.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.scheduling.quartz.SchedulerFactoryBean
import org.springframework.stereotype.Component
import org.quartz.Scheduler
import org.quartz.impl.StdSchedulerFactory


@Component
open class QuartzManager {

    @Qualifier("defaultScheduler")
    @Autowired
    private var scheduler: Scheduler? = null


    private val defaultScheduler: Scheduler = StdSchedulerFactory().scheduler

    /**
     * @Description: 添加一个定时任务
     *
     * @param jobName 任务名
     * @param jobGroupName  任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass  任务
     * @param cron   时间设置，参考quartz说明文档
     */
    fun addJob(jobName: String, jobGroupName: String,
               triggerName: String, triggerGroupName: String, jobClass: Class<Job>, cron: String) {
        try {
            // 任务名，任务组，任务执行类
            val jobDetail = JobBuilder.newJob(jobClass)
                    .withIdentity(jobName, jobGroupName).build()

            // 触发器
            val triggerBuilder = TriggerBuilder.newTrigger()
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName)
            triggerBuilder.startNow()
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron))
            // 创建Trigger对象
            val trigger = triggerBuilder.build() as CronTrigger


            scheduler?.let {


                // 调度容器设置JobDetail和Trigger
                it.scheduleJob(jobDetail, trigger)

                // 启动
                if (!it.isShutdown) {
                    scheduler!!.start()
                }
            }

            if (scheduler == null) {

                defaultScheduler.scheduleJob(jobDetail, trigger)
                defaultScheduler.start()

                println(" ---------- scheduler 是 空的！,使用 defaultScheduler .------------ ")
            }


        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

    /**
     * @Description: 修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param cron   时间设置，参考quartz说明文档
     */
    fun modifyJobTime(jobName: String,
                      jobGroupName: String, triggerName: String, triggerGroupName: String, cron: String) {
        try {
            val triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName)
            var trigger: CronTrigger? = scheduler!!.getTrigger(triggerKey) as CronTrigger ?: return

            val oldTime = trigger!!.cronExpression
            if (!oldTime.equals(cron, ignoreCase = true)) {
                /** 方式一 ：调用 rescheduleJob 开始  */
                // 触发器
                val triggerBuilder = TriggerBuilder.newTrigger()
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName)
                triggerBuilder.startNow()
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron))
                // 创建Trigger对象
                trigger = triggerBuilder.build() as CronTrigger
                // 方式一 ：修改一个任务的触发时间
                scheduler!!.rescheduleJob(triggerKey, trigger)
                /** 方式一 ：调用 rescheduleJob 结束  */

                /** 方式二：先删除，然后在创建一个新的Job   */
                //JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                //Class<? extends Job> jobClass = jobDetail.getJobClass();
                //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
                /** 方式二 ：先删除，然后在创建一个新的Job  */
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

    /**
     * @Description: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    fun removeJob(jobName: String, jobGroupName: String,
                  triggerName: String, triggerGroupName: String) {
        try {
            val triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName)

            scheduler!!.pauseTrigger(triggerKey)// 停止触发器
            scheduler!!.unscheduleJob(triggerKey)// 移除触发器
            scheduler!!.deleteJob(JobKey.jobKey(jobName, jobGroupName))// 删除任务
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

    /**
     * @Description:启动所有定时任务
     */
    fun startJobs() {
        try {
            scheduler!!.start()
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

    /**
     * @Description:关闭所有定时任务
     */
    fun shutdownJobs() {
        try {
            if (!scheduler!!.isShutdown) {
                scheduler!!.shutdown()
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

}
